package com.kwok.mybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtils {

    private static final ThreadLocal<SqlSession> sqlSessionThreadLocal = new ThreadLocal<SqlSession>();

    private static SqlSessionFactory sqlSessionFactory = null;

    static {
        //MyBatis核心配置文件只加载一次，并且sqlSessionFactory是共享的
        try {
            //1. 加载读取mybatis的核心配置文件（它也加载关联的映射文件），转为输入流
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            //2. 创建SqlSessionFactory工厂，将输入流传入进行构建
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public static SqlSession openSession(){
        //从当前线程中获取SqlSession对象
        SqlSession sqlSession = sqlSessionThreadLocal.get();
        if(sqlSession == null){
            //如果SqlSession对象为空，则创建一个新的SqlSession对象
            sqlSession = sqlSessionFactory.openSession();
            //将新的SqlSession对象与当前线程绑定
            sqlSessionThreadLocal.set(sqlSession);
        }
        return sqlSession;
    }

    /**
     * 封装事务
     * 提交事务
     * 回滚事务
     * 关闭事务
     */
    public static void commit(){
        SqlSession sqlSession = openSession();
        sqlSession.commit();
    }

    public static void rollback(){
        SqlSession sqlSession = openSession();
        sqlSession.rollback();
    }

    public static void close(){
        SqlSession sqlSession = openSession();
        sqlSession.close();
        sqlSessionThreadLocal.remove();
    }

    public static <T> T getMapper(Class<T> mapperClass){
        SqlSession sqlSession = openSession();
        //传入反射对象，返回实体对象
        return sqlSession.getMapper(mapperClass);
    }

    //每次获取不同的SqlSession连接对象，测试SqlSession级别的一级缓存查询
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }

}
